# -*- coding:utf-8 -*-
# anaconda python 3.8.5
# windows 10
from live_cals import LoadingLoop, futuredays, polyfitlize, Strategy_Main
from live_cals import polyfitlize_2 as polyfitlize
from strategy_mode import WAVE
from OtherTools.filetool import FileCheck
import numpy as np
import pandas as pd
import json
import gc
import re
import time


def range_gap(pre):
    pre_g = re.findall("\d*", pre)
    if pre_g != ["", ""]:
        gap = int(240 / int(pre))
    else:
        gap = 20
    return gap


def Main_cal(
    pre="15",
    code="300999",
    Cutting_start_date="2014-01-01",
    future_days=5,
    GroupOfLines=4,
    dirDic={
        "Main": "D:/StockDatas/",
        "basic": "basic/",
        "daily": "163_Daily_Bar/",
        "report": "Reports/",
        "temp": "temp/",
        "ticker": "History_ticker/",
        "mins": "History_mins/",
    },
):

    temppath = dirDic["Main"] + dirDic["temp"] + "{}_{}.csv".format(code, pre)
    print("code:{} pre:{}".format(code, pre).center(60, " "))

    chack = 0

    Ma_Day_List = WAVE.Waves(GroupOfLines - 1)
    line_Pares = len(Ma_Day_List) / (GroupOfLines)
    Ma_Day_List.sort()
    Ma_Day_List_Max = max(Ma_Day_List)

    if FileCheck(temppath):
        _df = pd.read_csv(temppath)
        _df.dropna(axis="index", how="all", subset=["high", "open","Avg"], inplace=True)
        chack = 1
        Ma_Day_List_Max =  Ma_Day_List_Max *3
        if _df.shape[0] > Ma_Day_List_Max:
            Cutting_start_date = _df.date.iloc[-(Ma_Day_List_Max)].split(" ")[0]
            print(Cutting_start_date)
            _df = _df.iloc[:-(Ma_Day_List_Max)]

    # TODO 添加旧文件缓存,加快计算速度
    stock_details, df = LoadingLoop.LoadingLoop(
        code, pre=pre, Cutting_start_date=Cutting_start_date
    )
    print(
        "post day:{} area:{} rows:{}".format(
            stock_details[0], "SH" if stock_details[1] == 0 else "SZ", df.shape[0]
        ).center(60, " ")
    )

    print("{} >> {}".format(df.date.iloc[0], df.date.iloc[-1]).center(60, " "))

    df.drop("index", axis=1, inplace=True)
    df = Strategy_Main.Strategy_Main(
        df,
        pre=pre,
        Ma_Day_List=Ma_Day_List,
        GroupOfLines=GroupOfLines,
        keyls=["close", "low", "high", "open", "Avg"],
    )

    gap = range_gap(pre)
    df = futuredays.futuredays(df, number_of_days=future_days, gap=gap * 2, pre=pre)
    df = polyfitlize.polyfitlize(df, "Avg", gap=gap, pre=pre)

    if chack == 1:
        df = pd.concat([_df, df])
        df.drop_duplicates("date", inplace=True, keep="first")
        df.sort_values("date", inplace=True)

    df.to_csv(temppath, index=False)
    print("done {}".format(temppath).center(60, " "))
    print()
    gc.collect()
    return df, stock_details
